import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/pages/driver_manage/driver_details/card_account_info/card_account_info_page.dart';
import 'package:nyh_motorcade_app/pages/driver_manage/driver_details/driver_details_controller.dart';
import 'package:nyh_motorcade_app/pages/driver_manage/driver_details/vehicle_info/vehicle_info_page.dart';
import 'package:nyh_motorcade_app/styles/colors.dart';
import 'package:nyh_motorcade_app/utils/format_utils.dart';
import 'package:nyh_motorcade_app/widgets/custom_app_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nyh_motorcade_app/widgets/flexible_icon_text.dart';
import 'package:nyh_motorcade_app/widgets/keep_alive_widget.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:nyh_motorcade_app/widgets/text_with_icon.dart';

class DriverDetailsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    String tag = DateTime.now().millisecondsSinceEpoch.toString();
    Get.put(DriverDetailsController(), tag: tag);
    return GetBuilder<DriverDetailsController>(
      tag: tag,
      builder: (controller) {
        return DefaultTabController(
          length: controller.tabTitle.length,
          child: Scaffold(
            backgroundColor: Colours.color_background,
            appBar: CustomAppBar(
              context: context,
              title: "司机详情",
              actions: [
                IconButton(
                  onPressed: () {
                    controller.goBackHomePage();
                  },
                  icon: Image.asset("images/ic_back_home.png"),
                ),
              ],
            ),
            body: MultiStateWidget(
              child: NestedScrollView(
                headerSliverBuilder: (context, innerBoxIsScrolled) {
                  return [
                    buildHeaderWidget(controller),
                    buildTabBarWidget(controller),
                  ];
                },
                body: TabBarView(
                  children: buildTabBarViewWidget(controller),
                ),
              ),
              state: controller.multiState,
              onRetry: () {
                controller.onRetry();
              },
            ),
          ),
        );
      },
    );
  }

  Widget buildHeaderWidget(DriverDetailsController controller) {
    List<String> quotaList = [];
    if (controller.entity?.refuelQuota != null) {
      quotaList.add("限额：${FormatUtils.formatMoney(controller.entity?.refuelQuota)}${controller.entity?.unitName ?? ""}/${controller.entity?.circleName ?? ""}");
    }
    if (controller.entity?.remainQuota != null) {
      quotaList.add("剩余：${FormatUtils.formatMoney(controller.entity?.remainQuota)}${controller.entity?.unitName ?? ""}/${controller.entity?.circleName ?? ""}");
    }
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.only(left: 16.w, top: 12.w, right: 16.w),
        decoration: BoxDecoration(
          color: Colours.color_white,
          borderRadius: BorderRadius.circular(10.w),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.symmetric(vertical: 13.w, horizontal: 16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Row(
                          children: [
                            Flexible(
                              child: Text(
                                controller.entity?.name ?? "",
                                style: TextStyle(
                                  color: Colours.color_text_theme,
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.bold,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            Visibility(
                              visible: (controller.entity?.belongingType ?? "").isNotEmpty,
                              child: Container(
                                margin: EdgeInsets.only(left: 8.w),
                                padding: EdgeInsets.only(left: 5.w, right: 5.w, bottom: 1.w),
                                decoration: BoxDecoration(
                                  color: (controller.entity?.belongingType ?? "") == Constant.OWN_DRIVER ? Colours.color_34c759 : Colours.color_theme,
                                  borderRadius: BorderRadius.circular(5.w),
                                  border: Border.all(width: 1.w, color: (controller.entity?.belongingType ?? "") == Constant.OWN_DRIVER ? Colours.color_34c759 : Colours.color_theme),
                                ),
                                child: Text(
                                  controller.entity?.belongingTypeName ?? "",
                                  style: TextStyle(
                                    color: Colours.color_white,
                                    fontSize: 10.sp,
                                  ),
                                ),
                              ),
                            ),
                            Visibility(
                              visible: controller.entity?.ifCardModel == 1,
                              child: Container(
                                margin: EdgeInsets.only(left: 8.w),
                                padding: EdgeInsets.only(left: 5.w, right: 5.w, bottom: 1.w),
                                decoration: BoxDecoration(
                                  color: Colours.color_white,
                                  borderRadius: BorderRadius.circular(5.w),
                                  border: Border.all(width: 1.w, color: Colours.color_6f7082),
                                ),
                                child: Text(
                                  "卡账户",
                                  style: TextStyle(
                                    color: Colours.color_6f7082,
                                    fontSize: 10.sp,
                                  ),
                                ),
                              ),
                            ),
                            Visibility(
                              visible: controller.entity?.status == 0,
                              child: Container(
                                margin: EdgeInsets.only(left: 8.w),
                                padding: EdgeInsets.only(left: 5.w, right: 5.w, bottom: 1.w),
                                decoration: BoxDecoration(
                                  color: Colours.color_cfcfd5,
                                  borderRadius: BorderRadius.circular(5.w),
                                  border: Border.all(width: 1.w, color: Colours.color_cfcfd5),
                                ),
                                child: Text(
                                  "已禁用",
                                  style: TextStyle(
                                    color: Colours.color_white,
                                    fontSize: 10.sp,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        width: 10.w,
                      ),
                      GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          controller.goToEditDriverInfoPage();
                        },
                        child: Padding(
                          padding: EdgeInsets.only(left: 5.w, top: 5.w, bottom: 5.w),
                          child: Image.asset("images/ic_edit.png"),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: ((controller.entity?.motorcadeName ?? "").isNotEmpty || (controller.entity?.phone ?? "").isNotEmpty) ? 7.w : 0,
                  ),
                  Row(
                    children: [
                      TextWithIcon(
                        text: controller.entity?.phone ?? "",
                        iconName: "images/ic_phone.png",
                        iconHeight: 14.w,
                        iconWidth: 14.w,
                        iconColor: Colours.color_6f7082,
                        textStyle: TextStyle(color: Colours.color_6f7082, fontSize: 12.sp),
                        textIconPadding: 5.w,
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 8.w),
                        child: Text(
                          "  l  ",
                          style: TextStyle(color: Colours.color_e7e7ea, fontSize: 12.sp),
                        ),
                      ),
                      Flexible(
                        child: TextWithIcon(
                          text: (controller.entity?.motorcadeName ?? "").isNotEmpty ? (controller.entity?.motorcadeName ?? "") : "无归属车队",
                          iconName: "images/ic_motorcade.png",
                          iconHeight: 14.w,
                          iconWidth: 14.w,
                          iconColor: Colours.color_6f7082,
                          textStyle: TextStyle(color: Colours.color_6f7082, fontSize: 12.sp),
                          textIconPadding: 5.w,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: (controller.entity?.subCompanyList ?? []).isNotEmpty ? 5.w : 0,
                  ),
                  FlexibleIconText(
                    icon: Image.asset(
                      "images/ic_company.png",
                      height: 14.w,
                      width: 14.w,
                      color: Colours.color_6f7082,
                    ),
                    textList: controller.entity?.subCompanyList,
                    iconTextPadding: 5.w,
                  ),
                  SizedBox(
                    height: 5.w,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Expanded(
                        child: FlexibleIconText(
                          textList: quotaList,
                          textStyle: TextStyle(color: Colours.color_text_theme, fontSize: 12.sp),
                        ),
                      ),
                      SizedBox(
                        width: 10.w,
                      ),
                      TextButton(
                        onPressed: () {
                          controller.goToTransactionFlowPage();
                        },
                        child: Text(
                          "交易流水",
                          style: TextStyle(
                            color: Colours.color_theme,
                            fontSize: 14.sp,
                          ),
                        ),
                        style: ButtonStyle(
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                          minimumSize: MaterialStateProperty.all(Size(80.w, 30.w)),
                          padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                          side: MaterialStateProperty.all(BorderSide(width: 1.w, color: Colours.color_theme)),
                          shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.w))),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Visibility(
              visible: (controller.entity?.remake ?? "").isNotEmpty,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Divider(
                    color: Colours.color_divider,
                    height: 1.w,
                    thickness: 1.w,
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 16.w),
                    child: Text(
                      controller.entity?.remake ?? "",
                      style: TextStyle(
                        color: Colours.color_cfcfd5,
                        fontSize: 12.sp,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildTabBarWidget(DriverDetailsController controller) {
    return SliverPersistentHeader(
      pinned: true,
      delegate: SliverTabBarDelegate(
        TabBar(
          tabs: controller.tabTitle.map((e) {
            return Tab(
              child: Text(e),
            );
          }).toList(),
          isScrollable: controller.tabTitle.length == 1,
          onTap: (index) {},
          indicatorWeight: 0,
          indicator: BoxDecoration(),
          labelColor: Colours.color_text_theme,
          unselectedLabelColor: Colours.color_6f7082,
          labelStyle: controller.entity!.ifCardModel == 1 ? TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold) : TextStyle(fontSize: 14.sp),
          unselectedLabelStyle: TextStyle(fontSize: 14.sp),
        ),
      ),
    );
  }

  List<Widget> buildTabBarViewWidget(DriverDetailsController controller) {
    List<Widget> list = [];
    switch (controller.tabTitle.length) {
      case 1:
        list.add(KeepAliveWidget(VehicleInfoPage(controller.driverId, controller.entity?.motorcadeId ?? "")));
        break;
      case 2:
        list.add(KeepAliveWidget(VehicleInfoPage(controller.driverId, controller.entity?.motorcadeId ?? "")));
        list.add(KeepAliveWidget(CardAccountInfoPage(controller.driverId, controller.cardList, (isEnable) {
          controller.setEnableEdit(isEnable);
        })));
        break;
      default:
    }
    return list;
  }
}

class SliverTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar tabBar;

  SliverTabBarDelegate(this.tabBar);

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colours.color_background,
      child: tabBar,
    );
  }

  @override
  double get maxExtent => tabBar.preferredSize.height;

  @override
  double get minExtent => tabBar.preferredSize.height;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}
